<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2017/12/23
 * Time: 下午4:58
 */

namespace Biz\module\Classes\adm;

use Biz\cache\GoodsSkuId;
use Biz\model\admin\AdminUser;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsExtendInfo;
use Biz\model\GoodsStockLog;
use Biz\model\OperateLog as mOperateLog;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\stat\GoodsTag;
use Biz\model\trade\Cart;
use Biz\module\Classes\core\SearchListAbstract;
use Biz\service\Goods;
use Biz\service\GoodsDetail;
use Biz\model\brand\Brand as mBrand;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Member;
use Biz\model\PhotoRelaGoods as bizPhotoRelaGoods;
use Doraemon\model\Spu as mSpu;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\tools\ImgUrl as toolImgUrl;
use Doraemon\tools\HhzEnv;
use Doraemon\cache\UserNick;
use Biz\service\SearchGoods;
use Biz\service\esSearch\Goods as esGoods;
use Biz\cache\counter\GoodsAddCart as cGoodsAddCart;

final class GoodsSearch extends SearchListAbstract
{
	private $results;

    protected function buildSelect()
    {
    }

    protected function buildWhere()
    {
        $statusMap = [
            'online' => mGoodsBasicInfo::STATUS_APP_NORMAL_MAP,
            'offline' => [mGoodsBasicInfo::STATUS_OFFLINE, mGoodsBasicInfo::STATUS_ADM_OFFLINE],
            'waitaudit' => [mGoodsBasicInfo::STATUS_WAIT_AUDIT]
        ];

        //状态
        if ($this->params['status']) {
            $this->where['status'] = $statusMap[$this->params['status']];
        }

        if ($this->params['brand_id'] > 0) {
            $this->where['brand_id'] = $this->params['brand_id'];
        }

        if ($this->params['category_id'] > 0) {
            $this->where['category_id'] = $this->params['category_id'];
        }

        if ($this->params['second_category_id'] > 0) {
            $this->where['second_category_id'] = $this->params['second_category_id'];
        }

        if ($this->params['third_category_id'] > 0) {
            $this->where['third_category_id'] = $this->params['third_category_id'];
        }

        if ($this->params['four_category_id'] > 0) {
            $this->where['four_category_id'] = $this->params['four_category_id'];
        }

        if ($this->params['start_date'] && $this->params['stop_date']) {

            $this->where['start_date'] = date("Y-m-d", strtotime($this->params['start_date']));
            $this->where['stop_date'] = date("Y-m-d", strtotime($this->params['stop_date']) + 86400);

//            $this->where['OR'] = [
//                'gbi.operate_time[<>]' => [$this->params['start_date'], date('Y-m-d', strtotime($this->params['stop_date']) + 86400)],
//                'gbi.operate_time' => '0000-00-00 00:00:00',
//            ];
        }


        //自定义搜索条件1

        if (!empty($this->params['field1'])) {

            if (!empty($this->params['keyword1'])) {
                if ($this->params['field1'] == 'uid') {
                    $this->where['shop_id'] = $this->params['keyword1'];
                } else if ($this->params['field1'] == 'uname') {
                	$results = AdmUserSearch::getUserIdsByFilter(['user_type' => [ Member::AUTH_USER_BRAND ], 'nick' => $this->params['keyword1']], 1);
                	if(!$results['rows']) {
                	    return $this->where = false;
                    }
					$this->where['shop_id'] = $results['rows'] ;
				}
            }
        }

        //自定义搜索条件2
        if (!empty($this->params['field2'])) {
            if (!empty($this->params['keyword2'])) {
                if ($this->params['field2'] == 'goods_id') {
                    if(is_numeric($this->params['keyword2'])) {
                        $this->where['id'] = $this->params['keyword2'];
                    }
                } else if ($this->params['field2'] == "title") {
					$this->where['title'] = $this->params['keyword2'];
				}
            }
        }


		if (isset($this->params['offline_type']) && $this->params['offline_type']) {
			if ($this->params['offline_type'] == 'hhz') {
				$this->where['operate_adminuid'] = 'hhz';
			} else if ($this->params['offline_type'] == 'shop') {
				$this->where['operate_adminuid'] = 'shop';
			}
		}


		if ($this->params['only_alarm'] == 'on') {
			$this->where['is_alarm'] = 1;
//            $this->join = ['[>]operate_log(ol)' => ['gbi.goods_id' => 'foreign_id']];
//            $this->where['ol.type'] = mOperateLog::TYPE_GOODS_ALARM;
        }

        //标签搜索
        if(!empty($this->params['tags_input'])){
            $this->where['tags_content'] = explode(' ',  $this->params['tags_input']);
        }

        if (isset($this->params['price_range'][0]) && $this->params['price_range'][0] != '') {
			$this->where['min_price_has_stock'] = $this->params['price_range'][0];
		}

        if (isset($this->params['price_range'][1]) && $this->params['price_range'][1] != '') {
            $this->where['max_price_has_stock'] = $this->params['price_range'][1];
        }

		if (!empty($this->params['sell_total'])) {
			$this->where['sell_total'] = $this->params['sell_total'];
		}
		if (!empty($this->params['add_cart_num'])) {
			$this->where['add_cart_num'] = $this->params['add_cart_num'];
		}

		if (!empty($this->params['sort'])) {
			$this->where['ORDER'] = $this->params['sort'];
		}

		$this->where['source'] = esGoods::SOURCE_SHOP_ADMIN;

		$this->where = array_filter($this->where);
    }

    public function getCount()
    {
        if($this->where === false) {
            return 0;
        }

    	$count = $this->results['total'];

        return $count;
    }

    public function nameToUids($name) {
//		$config = IniConfig::getConfigSelect('search_mod', 'user');
//		$path = $config['host'] . "/list";
		$uid =  UserNick::nick2uid($name);
		return $uid;

//		$filter['nick'] = $name;
//		$filter['nosegment'] = 1;
//		$filter['page'] = $page;
//		$filter['pagesize'] = AdmUserSearch::PAGE_SIZE;
//		$data = DCurl::Request("POST", $path, ['form_params'=> $filter]);
//		$data = json_decode($data['data'], true);
//		$results['total'] = $data['data']['total'];
//		$results['rows'] = $data['data']['rows'] ;
//		if ($uid) {
//			$results['total'] = $results['total'] + 1;
//			array_unshift($results['rows'], $uid);
//		}


	}

    public function getList()
    {
        if($this->where === false) {
            $this->results = [
                'is_over' => 1,
                'total' => 0,
                'rows' => [],
            ];
        } else {
            $this->results = SearchGoods::searchEntrance($this->where,esGoods::SCENES_SHOP_ADMIN_GOODS, 0, ($this->limit[0] / $this->limit[1]) + 1, $this->limit[1]);
        }

		$list = mGoodsBasicInfo::select("*", ['goods_id' => $this->results['rows']]);
        if ($list) {

            $uids = array_column($list, 'uid');
            $brandIds = array_column($list, 'brand_id');
            $categoryIds = array_merge(array_column($list, 'category_id'), array_column($list, 'second_category_id'), array_column($list, 'third_category_id'), array_column($list, 'four_category_id'));
            $wikiIds = array_column($list, 'wiki_id');
			$goodsIds = array_column($list, 'goods_id');
			$admin_uids = array_column($list, 'operate_adminuid');

			$goodsDetails = GoodsDetail::formatBasicInfos($goodsIds);


            $shopList = mShopBasicInfo::getInfoList($uids);
            $brandList = mBrand::getBrandListByIds($brandIds);
            $extendsInfo =  GoodsExtendInfo::getRemarksAndShippingTempl($goodsIds);
            $wikiList = array_column(mSpu::getSpuByIds($wikiIds, "*"), null, 'id');
            $categories = array_column(mCategory::getCategoryList($categoryIds, null), null, 'id');
//            $photoNums = PhotoRelaGoods::getPhotoNumGroupByGoods($wikiIds);
            $photoNums =bizPhotoRelaGoods::getPhotoNumGroupByGoods($goodsIds);
            $shopDomain = HhzEnv::detectShopDomain();
            $admin_userinfos = AdminUser::getAdminList($admin_uids);
            $memberCounts = Cart::admMemberNumsByGoodsIds($goodsIds);

            $list = array_column($list, null, 'goods_id');
            $result = [];
            if ($list) {
                foreach ($this->results['rows'] as &$goodsId) {
                    if (!isset($list[$goodsId])) continue;
                	$result[$goodsId] = $list[$goodsId];
                    $result[$goodsId]['shop_name'] = isset($shopList[$list[$goodsId]['uid']]) ? $shopList[$list[$goodsId]['uid']]['name'] : '';
                    $result[$goodsId]['brand_name'] = isset($brandList[$list[$goodsId]['brand_id']]) ? $brandList[$list[$goodsId]['brand_id']]['brand_name'] : '';
                    $result[$goodsId]['category'] = sprintf("%s-%s-%s-%s",
                        (isset($categories[$list[$goodsId]['category_id']]) ? $categories[$list[$goodsId]['category_id']]['cate_name'] : ''),
                        (isset($categories[$list[$goodsId]['second_category_id']]) ? $categories[$list[$goodsId]['second_category_id']]['cate_name'] : ''),
                        (isset($categories[$list[$goodsId]['third_category_id']]) ? $categories[$list[$goodsId]['third_category_id']]['cate_name'] : ''),
                        (isset($categories[$list[$goodsId]['four_category_id']]) ? $categories[$list[$goodsId]['four_category_id']]['cate_name'] : ''));
                    $result[$goodsId]['wiki'] = ['id' => $list[$goodsId]['wiki_id'], 'name' => isset($wikiList[$list[$goodsId]['wiki_id']]) ? $wikiList[$list[$goodsId]['wiki_id']]['title'] : ''];

                    $result[$goodsId]['remark'] = $extendsInfo[$list[$goodsId]['goods_id']]['remark'];

                    $result[$goodsId]['tags_content'] = $extendsInfo[$list[$goodsId]['goods_id']]['tags_content'];

                    $result[$goodsId]['goods_tag'] = '';

                    $result[$goodsId]['price_range'] = $goodsDetails[$list[$goodsId]['goods_id']]['min_price'] == $goodsDetails[$list[$goodsId]['goods_id']]['max_price'] ? $goodsDetails[$list[$goodsId]['goods_id']]['min_price'] : $goodsDetails[$list[$goodsId]['goods_id']]['min_price'] . ' - ' . $goodsDetails[$list[$goodsId]['goods_id']]['max_price'];

                    $result[$goodsId]['stock'] = $goodsDetails[$list[$goodsId]['goods_id']]['stock'];

                    $result[$goodsId]['photoNums'] = $photoNums[$goodsId];

                    $result[$goodsId]['sell_total'] = $list[$goodsId]['sell_total'];

                    $number = cGoodsAddCart::getAddCartNumber($goodsId);

                    $result[$goodsId]['allBuyNums'] = $number['goods'];

                    $result[$goodsId]['memberNums'] = $number['user'];

                    $result[$goodsId]['spec_img_url'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $list[$goodsId]['spec_img'], toolImgUrl::IMAGE_SIZE_ORI_NPHONE);

                    $result[$goodsId]['goods_h5_url'] = $shopDomain.'h5_goodsDetail/?goods_id='.$list[$goodsId]['goods_id'];

                    $result[$goodsId]['shipping_templ_id']=$extendsInfo[$list[$goodsId]['goods_id']]['shipping_templ_id'];

                    $result[$goodsId]['operate_adminname'] = isset($admin_userinfos[$list[$goodsId]['operate_adminuid']]) ? $admin_userinfos[$list[$goodsId]['operate_adminuid']]['name'] : '商家';

                    mGoodsBasicInfo::formatInfo($result[$goodsId], 'adm');
                }
            }

            return $result;
        }
    }

    public function download($fields, $page = 1, $pageSize = '*')
	{
		unset($fields['shop_name']);
		unset($fields['brand_name']);
        unset($fields['page']);
        if($this->where === false) {
             return [
                'is_over' => 1,
                'total' => 0,
                'rows' => [],
            ];
        } else {
            return SearchGoods::searchEntrance($this->where, esGoods::SCENES_SHOP_ADMIN_GOODS,0, $page, $pageSize, array_keys($fields));
        }
	}

}
